package com.dengdai.applibrary.json;

import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class Jackson {
    public static <T> List<T> getList(JSONArray array, Class<T> c) {
        List<T> list = new ArrayList<T>();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.getDeserializationConfig().set(org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            for (int i = 0; i < array.length(); i++) {
                T t = objectMapper.readValue(array.getString(i), c);
                list.add(t);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public static JSONObject getJSONObject(Object o) {
        JSONObject jsonObj = null;
        try {
            StringWriter sw = new StringWriter();
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(sw, o);
            jsonObj = new JSONObject(sw.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObj;
    }
}
